/**
 * Copyright 2005 SIB Framework

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.sibframework.utils;

import java.util.ArrayList;
import java.util.List;



public class IntervalsTool {
	private int intervals = 2000;
	private long lasttime = System.currentTimeMillis();
	private List<Object> runingInstances = new ArrayList<Object> ();
	

	public IntervalsTool() {
		super();
	}
	/**
	 * @param intervals intervals between two run in millisecond.
	 */
	public IntervalsTool(int intervals) {
		super();
		this.intervals = intervals;
	}
	
	public void intervalsRun(final Runnable runer) {
		intervalsRun(runer, this);
	}


	public void intervalsRun(final Runnable runer, final Object instance) {
		if (runingInstances.contains(instance)) {
			return;
		} else {
			runingInstances.add(instance);
		}
		new Thread((new Runnable(){
			public void run() {
				lasttime = System.currentTimeMillis();
				
				//intervals
				while (System.currentTimeMillis() - lasttime < intervals) {
					try {
						Thread.sleep(intervals);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
				//run
				runer.run();

				runingInstances.remove(instance);
				
				//System.out.println(SimpleDateFormat.getTimeInstance().format(Calendar.getInstance().getTime()) + " intervals run for " + instance.getClass().getSimpleName() + ":" + DefaultLabelProvider.getInstance().getText(instance));
				//
				lasttime = System.currentTimeMillis();
		}})).start();
	}
}
